package com.hundsun.s3.mrs.core.repeater;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hundsun.s3.mrs.core.task.Task;
import com.hundsun.s3.mrs.core.task.TaskManager;

/**
 * 核心转发器(线程池)
 * @author chenji23607
 *
 */
public class CoreRepeater implements Runnable {
	
	public static final String CORE_REP_NAME = "core repeater";
	
	private static final Logger LOG = LoggerFactory.getLogger(CoreRepeater.class);
	
	private static BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>();

	private int corePoolSize = 2;
	
	private int maxinumPoolSize = 5;
	
	private int keepAliveTime = 1;
	
	private TimeUnit timeUnit = TimeUnit.MINUTES;
	
	public CoreRepeater() {
		super();
		taskExecutorPool = new ThreadPoolExecutor(corePoolSize, maxinumPoolSize, keepAliveTime, timeUnit, workQueue);
	}
	public CoreRepeater(int corePoolSize, int maxinumPoolSize, int keepAliveTime, TimeUnit timeUnit) {
		super();
		this.corePoolSize = corePoolSize;
		this.maxinumPoolSize = maxinumPoolSize;
		this.keepAliveTime = keepAliveTime;
		this.timeUnit = timeUnit;
		taskExecutorPool = new ThreadPoolExecutor(corePoolSize, maxinumPoolSize, keepAliveTime, timeUnit, workQueue);
	}

	private static ThreadPoolExecutor taskExecutorPool;
	
	
	private static boolean running = true;
	
	@Override
	public void run() {
		List<Task> taskList;
		Task task;
		while(running) {
			synchronized (CoreRepeater.class) {
				taskList = TaskManager.getAll();
				Iterator<Task> iterator = taskList.iterator();
				while(iterator.hasNext()) {
					task = iterator.next();
					taskExecutorPool.execute(task);
				}
				// 所有的转发任务被处理完毕
				try {
					LOG.info("没有任务可以被处理，等待被唤醒...");
					TaskManager.clearAll();
					CoreRepeater.class.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}
		}
	}

	public static boolean isRunning() {
		return running;
	}

	public static void setRunning(boolean running) {
		CoreRepeater.running = running;
	}
	
}
